﻿using MediatR;
using Microsoft.IdentityModel.Tokens;
using SheepCultivation.Common.Domain.SheepBasicInformation;
using SheepCultivation.Common.Domain.Week2;
using SheepCultivation.Common.Dto;
using SheepCultivation.Common.Infrastructure.Interface;
using SheepCultivation.Enum;

namespace SheepCultivation.API.AddliCation.BreedingD
{
    public class SheepWeighedSeachHandler : IRequestHandler<SheepWeighedSeachCommon, Result>
    {
        #region 仓储
        /// <summary>
        /// 品种仓储
        /// </summary>
        public readonly IBaseRepository<Sheepvariety> SheepvarietyRepository;
        /// <summary>
        /// 羊只称重仓储
        /// </summary>
        public readonly IBaseRepository<SheepWeighed> SheepWeighedRepository;
        /// <summary>
        /// 耳号仓储
        /// </summary>
        public readonly IBaseRepository<BasicInformation> BasicInformationRepository;
        /// <summary>
        /// 栋舍仓储
        /// </summary>
        public readonly IBaseRepository<Building> BuildingRepository;
        /// <summary>
        /// 栋舍类型仓储
        /// </summary>
        public readonly IBaseRepository<BuildingType> BuildingTypeRepository;
        /// <summary>
        /// 栏位仓储
        /// </summary>
        public readonly IBaseRepository<Columns> ColumnsRepository;
        /// <summary>
        /// 体尺测定仓储
        /// </summary>
        public readonly IBaseRepository<Body> BodyRepository;
        /// <summary>
        /// 日志
        /// </summary>
        public readonly ILogger<SheepWeighedSeachHandler> logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sheepvarietyRepository">品种</param>
        /// <param name="SheepWeighedRepository">羊只称重</param>
        /// <param name="BasicInformationRepository"></param>
        /// <param name="BuildingRepository">耳号</param>
        /// <param name="BuildingTypeRepository">栋舍</param>
        /// <param name="ColumnsRepository">栋舍类型</param>
        /// <param name="BodyRepository">体尺测定</param>
        /// <param name="logger">日志</param>
        public SheepWeighedSeachHandler(IBaseRepository<Sheepvariety> sheepvarietyRepository, IBaseRepository<SheepWeighed> SheepWeighedRepository, IBaseRepository<BasicInformation> BasicInformationRepository, IBaseRepository<Building> BuildingRepository, IBaseRepository<BuildingType> BuildingTypeRepository, IBaseRepository<Columns> ColumnsRepository, IBaseRepository<Body> BodyRepository, ILogger<SheepWeighedSeachHandler> logger)
        {
            this.SheepvarietyRepository = sheepvarietyRepository;
            this.SheepWeighedRepository = SheepWeighedRepository;
            this.BasicInformationRepository = BasicInformationRepository;
            this.BuildingRepository = BuildingRepository;
            this.BuildingTypeRepository = BuildingTypeRepository;
            this.ColumnsRepository = ColumnsRepository;
            this.BodyRepository = BodyRepository;
            this.logger = logger;
        }

        #endregion

        #region 羊只称重显示
        /// <summary>
        /// 羊只称重 显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result> Handle(SheepWeighedSeachCommon request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonEnumCode.error };
            //异常处理
            try
            {
                DateTime today= DateTime.Today;
                logger.LogInformation("羊只称重显示成功!");
                var data = new pageDto() { };
                var list = (from a in SheepWeighedRepository.GetAll()
                            join b in BasicInformationRepository.GetAll() on a.BreedingSheepArchiveId equals b.BreedingSheepArchiveId
                            join c in SheepvarietyRepository.GetAll() on b.SheepbreedId equals c.SheepvarietyId
                            select new SheepWeighedDto()
                            {
                                SheepWeighedId = a.SheepWeighedId,
                                SheepWeighedTime = a.SheepWeighedTime,
                                Sexs = a.Sexs,
                                SheepWeighedType = a.SheepWeighedType,
                                SheepWeighedHeight = a.SheepWeighedHeight,
                                SheepWeighedAge = a.SheepWeighedAge,
                                BreedingSheepArchiveId = b.BreedingSheepArchiveId,
                                Auricle = b.Auricle,
                                SheepbreedId = b.SheepbreedId,
                                CorpuscleAuricle = b.CorpuscleAuricle,
                                GeneLV = b.GeneLV,
                                SheepTypeId = b.SheepTypeId,
                                SheepSex = b.SheepSex,
                                SheepvarietyId = c.SheepvarietyId,
                                SheepvarietyName = c.SheepvarietyName
                            }).ToList();

                //查询条件
                //开始称重日期
                if (!string.IsNullOrEmpty(request.begDate))
                {
                    list = list.Where(x => x.SheepWeighedTime >= DateTime.Parse(request.begDate)).ToList();
                }
                //结束称重日期
                if (!string.IsNullOrEmpty(request.endDate))
                {
                    list = list.Where(x => x.SheepWeighedTime <= DateTime.Parse(request.endDate).AddDays(1)).ToList();
                }

                //羊只耳号
                if (!string.IsNullOrEmpty(request.auricle))
                {
                    list = list.Where(x => x.Auricle.Contains(request.auricle)).ToList();
                }
                //称重类型
                if (request.sheepWeighedType > 0)
                {
                    list = list.Where(x => x.SheepWeighedType == request.sheepWeighedType).ToList();
                }
                //品种
                if (request.sheepvarietyId > 0)
                {
                    list = list.Where(x => x.SheepvarietyId == request.sheepvarietyId).ToList();
                }
                //性别
                if (request.sexs > 0)
                {
                    list = list.Where(x => x.Sexs == request.sexs).ToList();
                }
                //最小称重月龄
                if (request.startMonthAge > 0)
                { 
                    list = list.Where(x =>(today-x.SheepWeighedTime).TotalDays/30 >= request.startMonthAge).ToList();
                }
                //最大称重月龄
                if (request.endMonthAge > 0)
                {
                    list = list.Where(x => (today - x.SheepWeighedTime).TotalDays / 30 <= request.endMonthAge).ToList();
                }

                //分页
                data.totalCount = list.Count();
                data.pageCount = (int)((list.Count() * 1.0) / request.pageSize);
                data.data = list.OrderBy(x => x.SheepWeighedId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();

                result.Code = (int)CommonEnumCode.success;
                result.Data = data;
                result.Msg = "羊只称重显示成功";
            }
            catch (Exception ex)
            {
                logger.LogError("羊只称重显示失败!" + ex.Message);
                result.Msg = "羊只称重显示失败";
            }
            return result;
        }
        #endregion
    }

    /// <summary>
    /// 分页
    /// </summary>
    public class pageDto
    {
        public int totalCount { get; set; }
        public int pageCount { get; set; }
        public List<SheepWeighedDto> data { get; set; }
    }

    /// <summary>
    /// 羊只称重信息Dto
    /// </summary>
    public class SheepWeighedDto
    {
        /// <summary>
        /// 称重主键Id
        /// </summary>
        public int SheepWeighedId { get; set; }
        /// <summary>
        /// 称重日期
        /// </summary>
        public DateTime SheepWeighedTime { get; set; }
        /// <summary>
        /// 羊只耳号
        /// </summary>
        public int BreedingSheepArchiveId { get; set; }
        /// <summary>
        /// 性别
        /// </summary>
        public int Sexs { get; set; }

        /// <summary>
        /// 称重类型 1-断奶重 2-月龄重 3-出生重
        /// </summary>
        public int SheepWeighedType { get; set; }
        /// <summary>
        /// 重量（公斤）
        /// </summary>
        public decimal SheepWeighedHeight { get; set; }
        /// <summary>
        /// 称重月龄
        /// </summary>
        public int SheepWeighedAge { get; set; }
        /// <summary>
        /// 品种Id
        /// </summary>
        public int SheepvarietyId { get; set; }
        /// <summary>
        /// 品种名称
        /// </summary>
        public string? SheepvarietyName { get; set; }
        /// <summary> 
        /// 耳号
        /// </summary>
        public string Auricle { get; set; }
        /// <summary>
        /// 羊只品种Id
        /// </summary>
        public int SheepbreedId { get; set; }
        /// <summary>
        /// 电子耳号
        /// </summary>
        public string CorpuscleAuricle { get; set; }
        /// <summary>
        /// 基因等级
        /// </summary>
        public int GeneLV { get; set; }
        /// <summary>
        /// 羊只分类
        /// </summary>
        public int SheepTypeId { get; set; }
        /// <summary>
        /// 性别
        /// </summary>
        public int SheepSex { get; set; }
        /// <summary>
        /// 栋舍Id
        /// </summary>
        public int BuildingId { get; set; }

        /// <summary>
        /// 栋舍类型Id（栋舍类型表 BuildingType）
        /// </summary>
        public int BuildingTypeId { get; set; }

        /// <summary>
        /// 栋舍名称
        /// </summary>
        public string? BuildingName { get; set; }
        /// <summary>
        /// 负责人
        /// </summary>
        public string? BuildingPerson { get; set; }
        /// <summary>
        /// 生产人员
        /// </summary>
        public string? BuildingStaff { get; set; }
        /// <summary>
        /// 状态 1：启用 2：禁用
        /// </summary>
        public int BuildingState { get; set; }
        /// <summary>
        /// 备注
        /// </summary>
        public string? BuildingRenamk { get; set; }
    }

}
